package com.xust.oa.controller;

import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xust.oa.domain.dto.AdminDTO;
import com.xust.oa.domain.entity.TAdmin;
import com.xust.oa.domain.entity.TDepartment;
import com.xust.oa.domain.entity.TPosition;
import com.xust.oa.domain.vo.AdminVo;
import com.xust.oa.service.TAdminService;
import com.xust.oa.service.TDepartmentService;
import com.xust.oa.service.TPositionService;
import com.xust.oa.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zj
 * @time 2025/3/25 10:33
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private TAdminService adminService;

    @Value("${config.defaultPassword}")
    private String defaultPassword;

    @Autowired
    private TPositionService positionService;

    @Autowired
    private TDepartmentService departmentService;

    /**
     * 复杂查询人员信息数
     */
    @GetMapping("/count")
    public Result<Long> count(AdminDTO adminDTO) {

        String deptName = adminDTO.getDeptName();
        String positionName = adminDTO.getPositionName();
        QueryWrapper<TAdmin> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(adminDTO.getUsername()))
            queryWrapper.like("username", adminDTO.getUsername());
        if (!StringUtils.isEmpty(deptName))
            queryWrapper.eq("dept_id", getDeptId(deptName));
        if (!StringUtils.isEmpty(positionName))
            queryWrapper.eq("position_id", getPositionId(positionName));
        if (!StringUtils.isEmpty(adminDTO.getEnabled()))
            queryWrapper.eq("enabled", adminDTO.getEnabled());
        long count = adminService.count(queryWrapper);
        return Result.ok(count);
    }

    /**
     * 复杂查询人员信息
     *
     * @param adminDTO
     * @return
     */
    @PostMapping("/getList")
    public Result<List<AdminVo>> getList(@RequestBody AdminDTO adminDTO) {
        return adminService.getList(adminDTO);
    }

    /**
     * 新增人员
     */
    @PostMapping("/add")
    public Result add(@RequestBody TAdmin admin) {
        if (admin == null) return Result.buildFailure(400, "参数错误");
        MD5 md5 = new MD5();
        admin.setId(null);
        if (admin.getUsername() == null || admin.getName() == null) return Result.buildFailure(400, "参数不全");
        if (admin.getPassword() == null)
            admin.setPassword(md5.digestHex16(defaultPassword));
        String deptName = admin.getDeptName();
        if (!StringUtils.isEmpty(deptName)) {
            admin.setDeptId(getDeptId(deptName));
        }
        String positionName = admin.getPositionName();
        if (!StringUtils.isEmpty(positionName)) {
            admin.setPositionId(getPositionId(positionName));
        }
        if (admin.getPassword().length() < 6) return Result.buildFailure(400, "密码长度不能小于6位");
        try {
            adminService.save(admin);
            return Result.ok("人员添加成功");
        } catch (Exception e) {
            return Result.buildFailure(400, "用户名重复");
        }
    }

    private Integer getDeptId(String deptName) {
        List<TDepartment> departmentList = departmentService.list();
        Map<String, Integer> deptMap = new HashMap<>();
        for (TDepartment department : departmentList) {
            deptMap.put(department.getName(), department.getId());
        }
        return deptMap.get(deptName);
    }

    private Integer getPositionId(String positionName) {
        List<TPosition> positionList = positionService.list();
        Map<String, Integer> positionMap = new HashMap<>();
        for (TPosition position : positionList) {
            positionMap.put(position.getName(), position.getId());
        }
        return positionMap.get(positionName);
    }

    /**
     * 更新人员信息
     *
     * @param admin
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody TAdmin admin) {

        if (admin == null || admin.getId() == null) return Result.buildFailure(400, "ID不能为空");
        if (admin.getUsername() != null) return Result.buildFailure(400, "用户名不可修改");
        String deptName = admin.getDeptName();
        if (!StringUtils.isEmpty(deptName)) {
            admin.setDeptId(getDeptId(deptName));
        }
        String positionName = admin.getPositionName();
        if (!StringUtils.isEmpty(positionName)) {
            admin.setPositionId(getPositionId(positionName));
        }

        if (adminService.updateById(admin)) {
            return Result.ok("更新成功");
        }
        return Result.ok("更新成功");
    }

   /*    * 删除员工
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        TAdmin byId = adminService.getById(id);
        byId.setEnabled(0);
        if (adminService.updateById(byId)) return Result.ok("删除成功");
        return Result.buildFailure(400, "删除失败");
    }

}
